package com.salim.leetcode.$34;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FindFirstAndLastPositionOfElementInSortedArray {
    public int[] searchRange(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int[] result ={-1,-1};
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                result[0] = searchLeft(nums,left,mid,target);
                result[1] = searchRight(nums,mid,right,target);
                break;
            }else{
                if(nums[mid]<target){
                    left = mid + 1;
                }else{
                    right = mid - 1;
                }
            }
        }
        if(result[0]==-1 && result[1]==-1){

        }else{
            if(result[0] == -1){
                result[0] = result[1];
            }else if(result[1] == -1){
                result[1] = result[0];
            }
        }
        return result;
    }

    private int searchLeft(int[] nums,int left,int right,int target){
        int result = -1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                result = mid;
                right = mid - 1;
            }else{
                left = mid + 1;
            }
        }
        return result;
    }

    private int searchRight(int[] nums,int left,int right,int target){
        int result = -1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                result = mid;
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        FindFirstAndLastPositionOfElementInSortedArray f = new FindFirstAndLastPositionOfElementInSortedArray();
        log.info("SearchInRotatedSortedArray输出结果1：{}", f.searchRange(new int[]{5,7,7,8,8,10}, 8));
        log.info("SearchInRotatedSortedArray输出结果2：{}", f.searchRange(new int[]{5,7,7,8,8,10}, 6));
    }
}
